//
//  StatusDAL.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/28.
//  Copyright (c) 2015年 bing. All rights reserved.
//  数据访问层

import UIKit
import SDWebImage


private let WE_UNREAD_URL = "https://rm.api.weibo.com/2/remind/unread_count.json"
private let WE_Home_Timeline_URL = "https://api.weibo.com/2/statuses/home_timeline.json"

class StatusDAL: NSObject {
    
    // 创建数据表
    class func createTable() {
        let path = NSBundle.mainBundle().pathForResource("status", ofType: "sql")
        let data = NSData(contentsOfFile: path!)
        let sql = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
        println(sql)
        if SQLiteManager.sharedSQLiteManager().execSQL(sql) {
            println("表创建成功")
        } else {
            println("表创建失败")
        }
        
    }
    
    
    
    // 加载数据模型,用户登陆后加载数据
    class func DALloadStatus(since_Id since_id: Int, max_id: Int, complete:(statuses: [Status]?) -> ()) {

        
        // 数据库获取数据,有就从数据库获取
        let list = queryForSQLite3(since_Id: since_id, max_id: max_id)
        if  list?.count > 1 {
            complete(statuses: list)
            return
        }
    
        
        
        // 网络获取数据
        queryForNetwork(since_Id: since_id, max_id: max_id) { (statuses) -> () in
            complete(statuses: statuses)    
        }
        
        
    }
    
     /**
        重数据库获取缓存的微博
        SELECT * FROM User WHERE age > 10 ORDER BY height DESC LIMIT 20
    */
    private class func queryForSQLite3(since_Id since_id: Int, max_id: Int) -> [Status]?{
    
        var sql = "select status from Status Where uid = \(userInfoShared!.uid!) "
        
        if since_id > 0 {
            // 下拉刷新
            sql += "AND id > \(since_id) "
        } else if max_id > 0 {
            // 上拉刷新
            sql += "AND id < \(max_id) "
        }
        sql += "ORDER BY id DESC LIMIT 20 "
        
        
        // 注意查到的是字典数组
        let list = SQLiteManager.sharedSQLiteManager().querydatas(sql)
        var num = 0
        var array = [[String: AnyObject]]()
        while list?.count > num {
            let status = list![num++]
            let dictstring = status["status"] as! String
            let jsondata = dictstring.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
            let dict = NSJSONSerialization.JSONObjectWithData(jsondata, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String: AnyObject]
            
            array.append(dict)
        }
        
        // 获取数据信息后,需要缓存所有的图片信息,获取了返回值后计算cell高度
        if let result = Status.statusList(array) {
            
            // 在此处会将数据回调
            return result
        }
        
        return nil
    }
    
    
    /**
        从网络获取数据
    */
    private class func queryForNetwork(since_Id since_id: Int, max_id: Int, complete:(statuses: [Status]?)  -> ()){
        
        var params = ["access_token": userInfoShared!.access_token]
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        } else if max_id > 0 {
            params["max_id"] = "\(max_id - 1)"
        }
        
        NetWorkingTools.requestJSON(.GET, URLString: WE_Home_Timeline_URL, parameters: params) { (JSON) -> () in
            
            println("网络访问")
            if let array = (JSON as! NSDictionary)["statuses"] as? [[String: AnyObject]] {
                // 缓存数据到db中
                self.insertStatusToDB(array)
                
                // 获取数据信息后,需要缓存所有的图片信息,获取了返回值后计算cell高度
                if let result = Status.statusList(array) {
                    
                    // 在此处会将数据回调
                    self.cacheStatusImage(result, completion: complete)
                    return
                }
            }
            complete(statuses: nil)
        }
        
    }
    
    
    
    
    /**
        插入数据,到数据库做缓存
    */
    private class func insertStatusToDB(statuses: [AnyObject]?) -> Bool {
        let sql = "insert or replace into status(id,status,uid) values(?,?,?)"
        // 开启事物
        if SQLiteManager.sharedSQLiteManager().beginTransaction() {
            println("开启事务")
        }
    
        var result = false
        
        var count = 0
        let uid = userInfoShared?.uid
        while count < statuses?.count {
            let dict = statuses![count++] as! NSDictionary
            let id = dict["id"] as! Int
            
            // 装换为string
            let jsondata = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.allZeros, error: nil)
            let str = NSString(data: jsondata!, encoding: NSUTF8StringEncoding) as! String
            
            result = SQLiteManager.sharedSQLiteManager().batchUpdate(sql, params: id, str, uid!)
            
        }
        
        if result {
            SQLiteManager.sharedSQLiteManager().commitTransaction()
            println("提交事物")
        }
        
        if !result {
            SQLiteManager.sharedSQLiteManager().rollbackTransaction()
            println("回滚事物")
        }
        
        return result
    }
    
    
    
    // 缓存图片,图片下载完成后就能计算图片视图的宽度
    // 注意监听异步线程,当所有的图片缓存完成后,此时可以计算高度,显示cell
    private class func cacheStatusImage(statuses: [Status], completion:(statuses:[Status]?)->()) {
        // 使用调度组
        var group = dispatch_group_create()
        
        for status in statuses {
            if status.pictureURLs == nil {
                continue
            }
            
            // 缓存图片
            for url in status.pictureURLs! {
                dispatch_group_enter(group)
                // 当前只是用作缓存,不需要处理下载的图片,只是为了获取宽度
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: nil, progress: nil, completed: { (_, _, _, _, _) -> Void in
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 通知,当下载完成后通知回调数据
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            completion(statuses: statuses)
        }
    }
    
    
    // 清除缓存,清空7天前的缓存
    class func clearCache() {
        let fm = NSDateFormatter()
        fm.dateFormat = "yyyy-MM-dd HH:mm:ss"
        // 7 * 24 * 3600
        let data = fm.stringFromDate(NSDate(timeIntervalSinceNow: -7 * 24 * 3600))
        let sql = "delete from status where createDate < '\(data)'"
        if SQLiteManager.sharedSQLiteManager().execSQL(sql) {
            println("缓存清空了")
        }
    }
}
